package com.mapbased.sfw.component;

import java.util.List;

import org.dom4j.Element;

import com.mapbased.sfw.model.Fragment;
import com.mapbased.sfw.model.LoadContext;
import com.mapbased.sfw.model.NavItem;
import com.mapbased.sfw.model.RenderContext;
import com.mapbased.sfw.model.RenderGroup;

public class Nav extends Component {

	public static final Property[] properties = new Property[] {
				new Property.Int("level", "level") };

	int level;
	int varStart;
	private RenderGroup group;

	public Nav() {
	//	this.vars = new Object[3];
	}

	@Override
	public void render(RenderContext rc) {

		String path = rc.getPagePath();
		NavItem nav = rc.getSite().root;

		int i = path.indexOf("/");
		int lv = 0;
		String name = null;
		while (i > 0) {
			int j = path.indexOf("/", i + 1);
			if (j < 0) {
				break;
			}
			name = path.substring(i, j);
			if (lv == level || nav == null) {
				break;
			}
			nav = nav.getChild(name);

			i = j;
			lv++;
		}

		if (nav != null) {
			List<NavItem> items = nav.getChildren();
			for (int ii = 0; ii < items.size(); i++) {
				NavItem it = items.get(i);
				String s = "";
				if (ii == 0) {
					s = "first";
				} else if (ii == items.size()) {
					s = "last";
				}
				if (it.name.equals(name)) {
					s += " seleted";
				}
				rc.setVar(this.varStart+2, s);
				rc.setVar(this.varStart, it.getCaption());
				rc.setVar(this.varStart+1, it.getLink(path));
//				vars[3] = s;
//				vars[0] = it.getCaption();
//				vars[1] = it.getLink(path);
				this.group.render(rc);

			}

		}

		//		

	}
 

	@Override
	public String getTypeName() {

		return "Nav";
	}

	@Override
	public void parseXml(Element ele, LoadContext lc) {

		this.parseProperties(properties, ele, lc);
		varStart=lc.varIndex.getAndAdd(3);

		LoadContext lcc = lc.createChild();
		lcc.parseElement(ele);
		this.group = lcc.getRenderGroup();
	     lc.varIndex.addAndGet(-3);

	}

	@Override
	public void toXml(XmlContext xc) {
		
		xc.sb.append("<div jid=\"nav\" ");
		this.xmlProperties(properties, xc);

	}

	@Override
	public int mapVar(String name) {

		return name.equalsIgnoreCase("caption") ?varStart : name
				.equalsIgnoreCase("link") ? 1+varStart
				: name.equalsIgnoreCase("pos") ? varStart+2 : -1;

	}

}
